package com.example.compass2;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Context;
import android.hardware.Sensor;
import android.hardware.SensorEvent;
import android.hardware.SensorEventListener;
import android.hardware.SensorManager;
import android.os.Bundle;
import android.view.animation.Animation;
import android.view.animation.RotateAnimation;
import android.widget.ImageView;

public class compass extends AppCompatActivity implements SensorEventListener {
    //定义显示指南针的图片
    private ImageView znzIV;
    //记录指南针图片转过的角度
    private float currentDegree=0f;
    //定义Sensor管理器
    private SensorManager mSensorManager;

    public void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_compass);
        // 获取界面中显示指南针的图片
        znzIV = (ImageView) findViewById(R.id.znzImage);
        // 获取真机的传感器管理服务
        //	mSensorManager = (SensorManager)getSystemService(SENSOR_SERVICE);
// 获取传感器模拟器的传感器管理服务
        mSensorManager = (SensorManager)getSystemService(Context.SENSOR_SERVICE);
    }


    @Override
    protected void onResume() {
        super.onResume();
        //为系统的方向传感器注册监听器
        mSensorManager.registerListener(this,mSensorManager.getDefaultSensor(Sensor.TYPE_ORIENTATION),
                SensorManager.SENSOR_DELAY_GAME);
    }

    protected void onPause(){
        // 取消注册
        mSensorManager.unregisterListener(this);
        super.onPause();
    }


    @Override
    public void onSensorChanged(SensorEvent event) {
        //获取触发event的传感器类型
        int sensorType=event.sensor.getType();
        switch(sensorType)
        {
            case Sensor.TYPE_ORIENTATION;
                //获取绕z轴转过的角度
                float degree=event.values[0];
                //创建旋转动画（反向转degree度
                RotateAnimation ra=new RotateAnimation(currentDegree,-degree,
                        Animation.RELATIVE_TO_SELF,0.5f,
                        Animation.RELATIVE_TO_SELF,0.5f);
                //设置动画的持续触及
                ra.setDuration(200);
                //运行动画
                znzIV.startAnimation(ra);
                currentDegree=-degree;
                break;
        }

    }

    @Override
    public void onAccuracyChanged(Sensor sensor, int accuracy) {

    }
}
